
package com.map.core.utils;

import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * Title: Upload
 * Description:
 * @author DaiSn
 * @date 2019年3月13日
 */
public class Upload {
	public static void deleteFile(String path, HttpServletRequest request) {
		String temp = request.getSession().getServletContext().getRealPath("/");
		String clientPath = StringUtils.substringBefore(temp, "sanjiu");
		String finaPath = (clientPath + path).replace('\\', '/');
		File file = new File(finaPath + path);
		System.err.println(path);
		// 如果文件路径所对应的文件存在，并且是一个文件，则直接删除
		if (file.exists() && file.isFile()) {
			if (file.delete()) {
				System.out.println("删除单个文件" + path + "成功！");

			} else {
				System.out.println("删除单个文件" + path + "失败！");

			}
		} else {
			System.out.println("删除单个文件失败：" + path + "不存在！");

		}
	}

	/**
	 * 执行文件上传 直接传文件 linux已测试
	 * 
	 * @param file
	 * @return
	 * @throws MalformedURLException
	 * @throws Exception
	 */
	public static Map<String, String> upLoad(MultipartFile file, String path) {
		String uploadPath = "";
		Map<String, String> map = new HashMap<String, String>();
		URL url = null;
		// 用 当前日期+UUID作为文件名避免重名
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = sdf.format(new Date()).replaceAll("-", "");
		String name = dateStr + UUID.randomUUID().toString().replaceAll("-", "");//
		// 名称添加进返回Map中方便取出
		map.put("name", file.getOriginalFilename());
		// 获取文件类型，即后缀名
		String str = file.getOriginalFilename();
		String suffix = str.substring(str.lastIndexOf("."));
		// 绝对路径+生成的自动
		String finaPath = path + "/" + CommonUtils.getCurrentMonth().replaceAll("-", "") + name + suffix;
		uploadPath = path + "/" + CommonUtils.getCurrentMonth().replaceAll("-", "") + name + suffix;
		// 将uploadpath存入map中方便取出
		map.put("path", uploadPath);
		File uploadFile = new File(path);
		// 创建文件夹
		if (!uploadFile.exists()) {
			uploadFile.mkdirs();
		}
		try {
			file.transferTo(new File(finaPath));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return map;
	}
}
